package com.oulu.ruokkis.parser.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.oulu.ruokkis.model.Dish;
import com.oulu.ruokkis.model.Restaurant;
import com.oulu.ruokkis.parser.RSSMenuParser;

/**
 * 
 * @author antti.vainik@gmail.com
 *
 * RSS parser implementation for "Juissi RSS" 
 * 
 * This feed can be found at:
 * http://webcgi.oulu.fi/opiskelijalle/ruokalistat_rss.php
 */

public class RSSMenuParserJuissi implements RSSMenuParser{

	private final String TAG = "RSSMenuParserJuissi";
	private DocumentBuilderFactory dbf;
	private DocumentBuilder builder = null;
	private Document document;
	private Element root;	
	private Context context;
	
	public RSSMenuParserJuissi (Context context, String uri) {

		try {
			this.context = context;
			dbf = DocumentBuilderFactory.newInstance();
			builder = dbf.newDocumentBuilder();
			document = builder.parse(uri);
			root = document.getDocumentElement();
			root.normalize();
			
		} catch (ParserConfigurationException parserException) {
			
			String message = parserException.getMessage();
			Toast.makeText(this.context, "XML may be corrup", Toast.LENGTH_SHORT).show();
			Log.d(TAG, message);
			parserException.printStackTrace();
			System.exit(-1);
		} catch (SAXException e) {
			
			String message = e.getMessage();
			Toast.makeText(this.context, "XML may be corrup", Toast.LENGTH_SHORT).show();
			Log.d(TAG, message);
			e.printStackTrace();
			System.exit(-1);
		} catch (IOException e) {
			
			String message = e.getMessage();
			Toast.makeText(this.context, "No Internet?", Toast.LENGTH_SHORT).show();
			Log.d(TAG, message);
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public RSSMenuParserJuissi(Document document) {
		super();
		this.document = document;
		root = document.getDocumentElement();
		root.normalize();
		System.out.println("root: "+ root.getNodeName());
	}

	public List<Restaurant> parseAll() {

		List<Restaurant> restaurants = new ArrayList<Restaurant>();
		
		// restaurants
		NodeList nodes = document.getElementsByTagName("item");
		for (int i = 0; i < nodes.getLength(); i++) {
			Restaurant restaurant = new Restaurant();
			Element e = (Element) nodes.item(i);

			// Name of the restaurant
			NodeList list = e.getElementsByTagName("title");
			Element element = (Element) list.item(0);
			Text text = (Text) element.getFirstChild();
			String[] restaurantName = text.getNodeValue().split(" ");
//			System.out.println("title: " + text.getNodeValue());
			restaurant.setDate(restaurantName[0]);
			restaurant.setName(restaurantName[1]);

			// the Menu (html formatted)
			list = e.getElementsByTagName("description");
			element = (Element) list.item(0);
			text = (Text) element.getFirstChild();
//			System.out.println("description: " + text.getNodeValue());
			
			/*
			 * Menu for each restaurant looks like this.
			 * 
			<ul>
			  <li>Jauhelihapihvejä (M,saa M,G), tomaattista majoneesikastiketta (M,G) 220+35kcal/100g</li>
			  <li>Quornpihvejä (VL), tomaattista kasvismuhennosta (M,G)140+35kcal/100g</li>
			  <li>Fenkoli-yrttisosekeittoa (M,G) 41kcal/100g</li>
			  <li>Hedelmärahkaa (VL,G)</li>
			  <li>Minced meat steak with tomato and mayonnaise sauce</li>
			  <li>Quorn patties with tomato and mayonnaise sauce</li>
			  <li>Fennel and herbs purée soup</li>
			  <li>Fruit quark</li>
			</ul> 
			*/
			
			// split by rows
			String[] tags = text.getNodeValue().split("\\n");
			for (String string : tags) {
				
				// <li> rows contain actual Names, get them
				if(string.contains("<li>"))
				{
					string = string.replace("<li>", "");
					string = string.replace("</li>", "");
					string = string.trim();
					restaurant.add(new Dish(string));
//					System.out.println("dish: "+ dish);
				}
			}
			restaurants.add(restaurant);
		}

		return restaurants;
	}

}
